<script setup lang='ts'>
import { useAddOrEditJcOrgSys, useGetCreditCode } from '@fl/api/man-api'
import { SubmitBtn } from '@fl/components'
import { cloneDeep } from 'lodash-es'

import Seletct from './select.vue'

const { isPending, mutate } = useAddOrEditJcOrgSys()

const visible = defineModel<boolean>('visible', { required: true })

const enterpriseTypeOptions = defineModel<any>('enterpriseTypeOptions')

const groupOptions = defineModel<any>('groupOptions')

// const isSyn = ref(false)

const treeData = defineModel<any>('treeData')

const selectVisible = ref<boolean>(false)

const id = defineModel<any>('id')

const dialog = '新增组织'

const isSelect = ref(false)

const sourceEnum = {
    0: '集采商城',
    1: '城建集团',
}

const source = ref(sourceEnum[0])

const formRef = ref()

const ROOT_NODE = 'AJL-D-000001'

const initialState = {
    linkZzbm: '',
    orgName: '',
    orgShortName: '',
    orgStatus: '',
    orgType: '',
    parentCode: '',
    unifiedSocialCreditCode: '',
}

const state = ref<any>(cloneDeep(initialState))

const orgName = computed(() => state.value.orgName)
const { data: creditCodeData, refetch } = useGetCreditCode(orgName)

watchEffect(() => {
    if (creditCodeData.value) {
        state.value.unifiedSocialCreditCode = creditCodeData.value
    }
})

const orgTypeOptions = computed(() => {
    if (state.value?.parentCode === ROOT_NODE) {
        return [
            {
                label: '单位',
                value: 0,
            },
        ]
    }
    return [
        {
            label: '单位',
            value: 0,
        },
        {
            label: '部门',
            value: 1,
        },
    ]
})

const columns: any[] = [
    {
        colProps: {
            span: 12,
        },
        fieldProps: {
            onInput: () => {
                changeValue()
            },
        },
        label: '组织全称',
        prop: 'orgName',
    },
    {
        colProps: {
            span: 12,
        },
        fieldProps: {
            onInput: () => {
                changeValue()
            },
        },
        label: '组织简称',
        prop: 'orgShortName',
    },
    {
        colProps: {
            span: 12,
        },
        fieldProps: {
            filterable: true,
            onChange: () => {
                changeValue()
                state.value.orgType = null
            },
            props: {
                checkStrictly: true,
                children: 'childs',
                emitPath: false,
                label: 'orgName',
                value: 'orgCode',
            },
            showAllLevels: false,
        },
        label: '上级组织',
        options: treeData,
        prop: 'parentCode',
        valueType: 'cascader',
    },
    {
        colProps: {
            span: 12,
        },
        fieldProps: {
            onChange: () => {
                changeValue()
                state.value.unitType = null
            },
        },
        label: '组织类别',
        options: orgTypeOptions,
        prop: 'orgType',
        valueType: 'select',
    },
    {
        colProps: {
            span: 12,
        },
        fieldProps: {
            disabled: true,
        },
        hideInForm: computed(() => state.value.orgType !== 0),
        label: '统一社会信用代码',
        prop: 'unifiedSocialCreditCode',
        valueType: 'input',
    },
    {
        colProps: {
            span: 12,
        },
        fieldProps: {
            onChange: () => {
                changeValue()
            },
        },
        label: '组织状态',
        options: [
            {
                label: '停用',
                value: 0,
            },
            {
                label: '启用',
                value: 1,
            },
        ],
        prop: 'orgStatus',
        valueType: 'select',
    },
    {
        colProps: {
            span: 12,
        },
        fieldProps: {
            // onChange: () => {
            //     changeValue()
            // },
        },
        hideInForm: computed(() => state.value.orgType !== 0),
        label: '单位类型',
        options: enterpriseTypeOptions,
        prop: 'unitType',
        valueType: 'select',
    },
    {
        colProps: {
            span: 12,
        },
        fieldProps: {
            // onChange: () => {
            //     changeValue()
            // },
        },
        label: '所属集团',
        options: groupOptions,
        prop: 'groupId',
        valueType: 'select',
    },
]

const rules = {
    orgName: [
        {
            message: '请选择单位类型',
            required: true,
            trigger: ['blur', 'change'],
        },
    ],
    orgStatus: [
        {
            message: '请输入组织状态',
            required: true,
            trigger: ['blur', 'change'],
        },
    ],
    orgType: [
        {
            message: '请选择组织类别',
            required: true,
            trigger: ['blur', 'change'],
        },
    ],
    parentCode: [
        {
            message: '请选择上级组织',
            required: true,
            trigger: ['blur', 'change'],
        },
    ],
    unifiedSocialCreditCode: [
        {
            message: '请输入统一社会信用代码',
            required: true,
            trigger: ['blur', 'change'],
        },
    ],
    unitType: [
        {
            message: '请输入组织全称',
            required: true,
            trigger: ['blur', 'change'],
        },
    ],
}

function cancel() {
    visible.value = false
}

function reset() {
    id.value = ''
    formRef.value.formInstance.resetFields()
    state.value = cloneDeep(initialState)
}

function transfer(val: any) {
    console.log('🚀 ~ transfer ~ val:', val)
    const params = {
        groupId: state.value?.groupId,
        linkZzbm: val?.ZZ_ZZBM,
        orgName: val?.ZZ_ZZQC,
        orgShortName: val?.ZZ_ZZJC,
        orgStatus: val?.ZZ_ZZZTDM,
        orgType: state.value?.parentCode === ROOT_NODE ? 0 : val?.ZZ_ZZLB === '单位' ? 0 : 1,
        parentCode: state.value?.parentCode || ROOT_NODE,
    }
    state.value = cloneDeep(params)
    source.value = sourceEnum[1]
    isSelect.value = true
    getCreditCodeName()
}

async function confirm() {
    const valid = await formRef.value.formInstance.validate()
    if (valid) {
        const params = {
            ...state.value,
            source: source.value,
            type: 'add',
        }
        console.log('🚀 ~ confirm ~ params:', params)
        if (params.orgType === 1 && params.unifiedSocialCreditCode) {
            params.unifiedSocialCreditCode = ''
        }
        mutate(params, {
            onSuccess: () => {
                ElMessage.success('操作成功')
                cancel()
            },
        })
    }
}

function getCreditCodeName() {
    if (!state.value.orgName)
        return
    refetch()
}

function changeValue() {
    console.log('🚀 ~ changeValue ~ ')
    if (!isSelect.value) {
        return
    }
    source.value = sourceEnum[0]
}

function showSelect() {
    selectVisible.value = true
}
</script>

<template>
    <PlusDialog v-model="visible"
                :title="dialog"
                width="800"
                @cancel="cancel"
                @closed="reset"
    >
        <PlusForm ref="formRef"
                  v-model="state"
                  :columns="columns"
                  :label-width="130"
                  :has-footer="false"
                  :rules="rules"
                  label-position="top"
                  class="max-h-600 overflow-x-hidden overflow-y-auto"
                  :row-props="{ gutter: 20 }"
        >
            <template #plus-field-orgName>
                <div class="flex gap-10 w-full">
                    <el-input v-model="state.orgName"
                              class="flex-1"
                              placeholder="请输入"
                              clearable
                              @input="changeValue"
                              @blur="getCreditCodeName"
                    />

                    <el-button type="primary"
                               @click="showSelect"
                    >
                        选择
                    </el-button>
                </div>
            </template>
        </PlusForm>

        <template #footer>
            <div class="mx-auto">
                <el-button @click="cancel">
                    取消
                </el-button>

                <SubmitBtn type="primary"
                           :loading="isPending"
                           @click="confirm"
                >
                    提交
                </SubmitBtn>
            </div>
        </template>
    </PlusDialog>

    <Seletct v-model:visible="selectVisible"
             @transfer="transfer"
    />
</template>
